<template>
  <el-container>
    <el-header><NavBar activeIndex="1"></NavBar></el-header>
    <el-main
      ><el-row>
        <el-col :md="14"
          ><div class="loan-container">
            <el-card class="box-card">
              <div class="title-container">
                <span>借款申请表</span>
              </div>
              <el-form
                label-position="left"
                :model="loanApplyForm"
                :rules="rules"
                ref="loanApplyForm"
                label-width="100px"
                class="demo-loanApplyForm"
              >
                <el-form-item label="借款人" prop="holder">
                  <el-input readonly placeholder="请先登录" v-model="loanApplyForm.holder"></el-input>
                </el-form-item>
                <el-form-item label="借款金额" prop="amount">
                  <el-input @change="onAmountChange"
                    v-model="loanApplyForm.amount"
                  ></el-input>
                </el-form-item>
                <el-form-item label="还款方式" prop="holder">
                  <el-radio v-model="radio" label="1">等额本金</el-radio>
                </el-form-item>
                <el-form-item label="借款利率" prop="holder">
                  <span>年利率{{yearRate}}%</span>
                </el-form-item>
                <el-form-item label="借款期限" prop="loanMonth">
                  <el-dropdown @command="onSelect">
                    <span class="el-dropdown-link">
                      {{ loanMonthTxt
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item command="3">3个月</el-dropdown-item>
                      <el-dropdown-item command="6">6个月</el-dropdown-item>
                      <el-dropdown-item command="12">12个月</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-form-item>
                <el-form-item label="还款计划" prop="holder">
                  <el-popover placement="right" trigger="click">
                    <el-table :data="repayPlanData">
                      <el-table-column
                        width="150"
                        property="date"
                        label="还款日期"
                      ></el-table-column>
                      <el-table-column
                        width="400"
                        property="repayInfo"
                        label="还款金额"
                      ></el-table-column>
                    </el-table>
                    <el-button slot="reference">详情点击</el-button>
                  </el-popover>
                </el-form-item>
                <el-form-item v-if="name" label="手机号" prop="holder">
                  <span>{{accountStatus.phone}}</span>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-input
                    class="sort-input"
                    v-model.number="loanApplyForm.code"
                  ></el-input>
                  <el-button :disabled="!name || !sendBtnAble" @click="sendMsg" type="primary">{{
                    sendBtnTxt
                  }}</el-button>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="submitForm('loanApplyForm')"
                    >提交借款申请</el-button
                  >
                </el-form-item>
              </el-form>
            </el-card>
          </div></el-col
        >
        <el-col :md="10" class="hidden-sm-and-down">
          <div class="img-box">
            <el-image :src="require('@/assets/loan.png')"></el-image>
          </div>
        </el-col> </el-row
    ></el-main>
  </el-container>
</template>

<script>
import { authLogin } from "@/utils/auth";
import NavBar from "@/components/NavBar";
import { mapActions, mapGetters } from "vuex";
export default {
  name: "LoanApply",
  components: {
    NavBar,
  },
  data() {
    // 自定义借款金额校验器
    var checkAmount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("金额不能为空"));
      }
      setTimeout(() => {
        const regAmount = /^(?!0)\d{1,6}$/
        if(regAmount.test(value)){
          callback()
        }else{
          callback(new Error('请输入1到6位正整数'))
        }
      }, 500);
    };
    return {
      yearRate:5.5,
      sendBtnAble:true,
      conter:10,
      sendBtnTxt: "发送验证码",
      radio: "1",
      loanMonthTxt: "请选择",
      // 借款表单绑定的数据
      loanApplyForm: {
        // 借款人
        holder: "",
        // 借款金额
        amount: "",
        // 借款月数
        loanMonth:'',
        code: "",
      },
      repayPlanData: [
        
      ],
      rules: {
        amount: [{ validator: checkAmount, trigger: "blur" }],
        code: [
          { required: true, message: "验证码不能为空" },
          { type: "number", message: "必须为数字" },
        ],
        loanMonth: [
          { required: true, message: "请选择借款期限", trigger:'change' },
        ],
      },
    };
  },
  methods: {
    ...mapActions({
      getSmsCode: "user/getSmsCode",
      loanApply:'loan/loanApply'
    }),
    // 当借款金额发生变化
    onAmountChange(){
      this.getRepayPlan()
    },
    // 生成还款计划
    getRepayPlan(){
      if(this.loanApplyForm.amount && this.loanApplyForm.loanMonth){
        // 每个月还款的本金 借款金额 / 借款期数
        var monthCost = (this.loanApplyForm.amount / this.loanApplyForm.loanMonth).toFixed(2)
        // 月利率
        var monthRate = (this.yearRate / 100 / 12).toFixed(4);
        // 月利息
        var monthInterest = 0;
        // 每个月要换的总金额
        var totalAmount = 0;
        this.repayPlanData = []
        for (let index = 1; index <= this.loanApplyForm.loanMonth; index++) {
          monthInterest = ((this.loanApplyForm.amount - monthCost * (index - 1)) * monthRate).toFixed(2)
          totalAmount = (parseFloat(monthCost)  + parseFloat(monthInterest)).toFixed(2)

          var now = new Date();
          var year = now.getFullYear();
          var month = now.getMonth() + 1 + index
          var date = now.getDate()
          if(month > 12){
            month -= 12
            year += 1
          }

          var repayDate = `${year}年${month}月${date}日`
          var repayInfo = `本金:${monthCost},利息:${monthInterest},还款总额(本金+利息):${totalAmount}`

          var repayItem = { date:repayDate, repayInfo:repayInfo}
          this.repayPlanData.push(repayItem)
        }
      }
    },
    // 提交表单
    submitForm(formName) {
      if (authLogin(this)) {
        this.sendLoanAplly(formName)
      }
    },
    sendLoanAplly(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loanApply(this.loanApplyForm).then((res) => {
            this.$message({
              message: "借款申請成功，等待审核",
              type: "success",
            });
            setTimeout(() => {
              this.$router.push('/')
            }, 5000);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 发送验证码
    sendMsg() {
      // this.isRightPhone = false
      this.getSmsCode({ phone: this.accountStatus.phone })
        .then((res) => {
          this.sendBtnAble = false
          this.$notify({
            title: "验证码",
            message: res.smsCode,
            type: "success",
          });
          this.countDown();
        })
        .catch((err) => {
          this.sendBtnAble = true
        });
    },
    // 倒计时开始
    countDown() {
      this.timer = setInterval(() => {
        this.sendBtnTxt = `${this.conter}秒`;
        this.conter--;
        if (this.conter < 0) {
          this.reset();
        }
      }, 1000);
    },
    // 重置计时器
    reset() {
      this.sendBtnAble = true
      this.sendBtnTxt = "发送验证码";
      if (this.timer) {
        clearInterval(this.timer);
        this.conter = 10;
        this.timer = null;
      }
    },
    // 选择借款期数的回调方法
    onSelect(data) {
      console.log(data);
      this.loanMonthTxt = `${data}个月`;
      this.loanApplyForm.loanMonth = data
      this.$refs.loanApplyForm.validateField('loanMonth');
      this.getRepayPlan()
    },
  },
  computed: {
    ...mapGetters([
      "name",
      "accountStatus",
      // ...
    ]),
  },
  created(){
    this.loanApplyForm.holder = this.name
  }
};
</script>

<style lang="scss" scoped>
.loan-container {
  height: 100%;
  width: 100%;
  padding-top: 120px;

  .box-card {
    min-height: 500px;
    max-width: 450px;
    margin: 0px auto;
    background-color: #e9eef3;

    .title-container {
      text-align: center;
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 15px;
    }

    .sort-input {
      width: 80px;
      margin-right: 15px;
    }

    .el-dropdown-link {
      cursor: pointer;
      color: #409eff;
    }
  }
}

.el-row {
  height: 100%;
  .el-col {
    height: 100%;
  }
}

.el-main {
  background-color: #ffd101;

  .img-box {
    padding-top: 125px;
  }
}
</style>